package com.zyb.warehouse.service.impl;

import com.zyb.warehouse.common.Result;
import com.zyb.warehouse.dto.Page;
import com.zyb.warehouse.entity.CurrentUser;
import com.zyb.warehouse.entity.OutStore;
import com.zyb.warehouse.entity.Product;
import com.zyb.warehouse.mapper.OutStoreMapper;
import com.zyb.warehouse.mapper.ProductMapper;
import com.zyb.warehouse.service.OutStoreService;
import com.zyb.warehouse.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Description:出库表业务层接口实现类
 */
@Service
public class OutStoreServiceImpl implements OutStoreService {

    @Autowired
    private OutStoreMapper outStoreMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private TokenUtils tokenUtils;

    /**
     * 添加出库单
     *
     * @param outStore
     * @return
     */
    public Result addOutStore(OutStore outStore, String token) {
        //获取前端传递过来的token
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        //设置属性
        outStore.setTallyId(currentUser.getUserId());//理货人ID暂时先给当前登录用户ID
        outStore.setCreateBy(currentUser.getUserId());
        //进行添加
        Integer i = outStoreMapper.insertOutStore(outStore);
        if (i > 0) {
            return Result.ok("添加出库单成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "添加出库单成功");
    }

    /**
     * 分页查询出库单
     *
     * @param page
     * @param outStore
     * @return
     */
    public Page pageOutStore(Page page, OutStore outStore) {
        //查询总记录数
        Integer count = outStoreMapper.selectOutStoreTotal(outStore);
        //查询所有入库单带分页
        List<OutStore> outStoreList = outStoreMapper.pageOutStore(page, outStore);
        //属性拷贝
        page.setTotalNum(count);
        page.setResultList(outStoreList);
        return page;
    }

    /**
     * 确认出库
     *
     * @param outStore
     * @return
     */
    @Transactional
    public Result confirmOutStore(OutStore outStore) {
        //判断库存是否充足
        Product product = productMapper.selectProductById(outStore.getProductId());
        if (product.getProductInvent() < outStore.getOutNum()) {
            return Result.err(Result.CODE_ERR_BUSINESS, "库存不足");
        }
        //修改出库单状态为已出库
        Integer i = outStoreMapper.updateIsOutState(outStore.getOutsId());
        if (i > 0) {
            //把出库的实际数量和原来的库存相减
            Integer j = productMapper.updateProductInventById(outStore.getProductId(), -outStore.getOutNum());
            if (j > 0) {
                return Result.ok("确认出库成功");
            }
            return Result.err(Result.CODE_ERR_BUSINESS, "确认出库失败");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "确认出库失败");
    }
}
